package com.youlai.boot.common.util;

import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

@Component
public class WeChatDecryptUtil {
    
    /**
     * 解密方法
     * 
     * @param sessionKey 会话密钥
     * @param encryptedData 加密的用户数据
     * @param iv 初始化向量
     * @return 解密后的原始数据
     * @throws Exception
     */
    public static String decryptData(String sessionKey, String encryptedData, String iv) throws Exception {
        // 将 Base64 编码的数据解码
        byte[] sessionKeyBytes = Base64.getDecoder().decode(sessionKey);
        byte[] encryptedDataBytes = Base64.getDecoder().decode(encryptedData);
        byte[] ivBytes = Base64.getDecoder().decode(iv);
        
        // 使用 AES CBC 模式解密
        SecretKeySpec secretKey = new SecretKeySpec(sessionKeyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, new javax.crypto.spec.IvParameterSpec(ivBytes));
        
        byte[] decryptedBytes = cipher.doFinal(encryptedDataBytes);
        
        // 将解密后的字节数组转换为字符串
        String decryptedData = new String(decryptedBytes, "UTF-8");
        
        return decryptedData;
    }

}
